package com.lagou.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.internet.MimeMessage;

/**
 * 邮件微服务控制层类
 * @author yzh
 * @date 2020/5/1 14:39
 */
@RestController
@RequestMapping("/api/email")
@RefreshScope
public class EmailController {

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String username;

    @GetMapping("/getApplicationName")
    public String getApplicationName() {
        return applicationName;
    }

    /**
     * 发送邮件的方法
     * @param email 收件方邮箱
     * @param code 验证码
     * @return 发送结果
     */
    @GetMapping("/sendEmail/{email}/{code}")
    public boolean sendEmail(@PathVariable String email, @PathVariable String code) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = null;
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(email);
            helper.setSubject("验证码");
            helper.setText(code, true);
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
